// const { query } = require("express");
let db = require("../db/index");
const jwt = require('jsonwebtoken');
const { Base64 } = require('js-base64');  // 引入 Base64 模块
let { JWT_SECRET } = require('../jwtAuth')
const { hashPassword, verifyPassword } = require('../encryptionService');
const SMSClient = require('@alicloud/sms-sdk'); //导入模块
/* GET users listing. */
//初始化sms_client
let smsClient = new SMSClient({
    accessKeyId: "LTAI5tAv11ig3yWwT3epRQuM",
    secretAccessKey: "hQElwdXVU8y6wwepCPnEg1mFo3aspo"
})//阿里云上的id和密钥//验证码
// const codesArr=[]
// 用户登录路由
exports.login = (req, res) => {
    const { name, pwd } = req.body;
    const password = Base64.decode(pwd);
    var sql = `select employee.*,RoleState from role,employee where role.ID=employee.RoleID and employee.Account='${name}'`;

    db.query(sql, [], async (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }


        const accountState = data.every(item => item.Status == '启用')
        //判断状态
        if (!accountState) {
            return res.send({
                msg: '该账号未启用,请联系管理员'
            });
        }
        const rolePermission = data.every(item => item.RoleState == '启用')
        if (!rolePermission) {
            return res.send({
                msg: '暂未权限,请联系超级管理员'
            });
        }
        console.log(data);

        const user = data.find(u => u.Account === name);
        console.log(user);

        if (!user) {


            return res.sendStatus(400); // 如果用户名或密码不正确，返回 400 Bad Request
        }
        if (await verifyPassword(password, user.Password)) {
            // 生成 JWT
            const payload = { username: user.username };
            const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' }); // Token 有效期为 1 小时
            res.json([token, user.Account, user.RoleID]); // 将 Token 发送给客户端
        } else {
            return res.send({
                msg: '密码错误,请联系超级管理员或忘记密码'
            });
        }
    });
};
let codes = "";
//获取验证码
exports.getCode = (req, res) => {
    const { phone } = req.body
    var sql = `select PhoneNumber from employee where PhoneNumber='${phone}'`
    db.query(sql, [], async (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        if (!data[0]) {
            //查找不到该手机号
            res.send({
                msg: '该用户不存在'
            })
            return
        }
        codes = "";
        for (let i = 0; i < 6; i++) {
            codes = codes + Math.floor(Math.random() * 10);
        }
        // codesArr.push(codes)
        console.log(codes, 77777);
        smsClient.sendSMS({
            PhoneNumbers: phone,
            SignName: '物业后台管理',//必填:短信签名-可在短信控制台中找到　　　//
            TemplateCode: 'SMS_476455108',//必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台
            TemplateParam: `{\"code\":\"${codes}\"}`
        }).then(function (res1) {
            let { Code } = res1
            if (Code === 'OK') {
                //处理返回参数
                res.send({
                    success: '发送成功,请注意查收',
                    // state:codesArr[codesArr.length-1]
                })

            }
        }, function (err) {
            console.log(err, 55555);
        });
    })
};
//通过验证码修改密码
exports.forgetPwd = async (req, res) => {
    console.log(req.body);
    const { phone, code, pass } = req.body
    if (code != codes) {
        res.send({
            msg: '验证码输入有误'
        })
        return
    }

    const password = await hashPassword(pass)
    var sql =
        `update employee set Password='${password}' where PhoneNumber='${phone}'`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send({
            success: '密码修改成功'
        });
    });



};
//通过验证码登录
exports.codeLogin = (req, res) => {
    console.log(req.body);

    const { phone, code } = req.body
    if (codes != code) {
        res.send({
            msg: '验证码输入有误,请重新输入'
        })
    }

    var sql =
        `select Account,RoleID from employee where PhoneNumber='${phone}'`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        console.log(data, 88888);

        const payload = { username: data[0].Account };
        const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' }); // Token 有效期为 1 小时

        res.json([token, data[0].Account, data[0].RoleID]); // 将 Token 发送给客户端
    });
};
//所有的信息
exports.all = (req, res) => {
    var sql =
        'SELECT employee.*,RoleName from role,employee where role.ID=employee.RoleID';
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send(data);
    });
};
//修改数据启用和停用
exports.update = (req, res) => {
    var sql =
        `update employee set Status='${req.body.str}' where ID=${req.body.id};`;


    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send({
            status: 500
        });
    });
}
//修改具体数据
exports.AllUpdate = (req, res) => {
    console.log(req.body)
    const { name, num, type, cardID, role, BuildingJurisdiction, id } = req.body

    var sql =
        `select ID from role where RoleName='${role}'`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        console.log(data[0].ID);
        var sql =
            ` update employee set Name='${name}',PhoneNumber='${num}',CardType='${type}',CardID='${cardID}',RoleID='${data[0].ID}',BuildingJurisdiction='${BuildingJurisdiction}'  where ID=${id};`;
        db.query(sql, [], (err, data) => {
            if (err) {
                console.log("出错了", err);
                return res.send("错误" + err.message);
            }
            res.send({
                status: 500
            });
        });

    });

}
//添加数据
exports.add = (req, res) => {
    console.log(req.body);
    const { name, account, num, IC, role, BuildingJurisdiction, type, cardID } = req.body
    var sql =
        `select ID from role where RoleName='${role}'`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        console.log(data[0].ID, 8888);
        var sql =
            `insert into employee(Name,Account,PhoneNumber,ICCardNumber,RoleID,BuildingJurisdiction,CardType,CardID)values('${name}','${account}','${num}','${IC}','${data[0].ID}','${BuildingJurisdiction}','${type}','${cardID}');`;

        db.query(sql, [], (err, data) => {
            if (err) {
                console.log("出错了", err);
                return res.send("错误" + err.message);
            }
            res.send({
                status: 500
            });
        });
    })


}
//导入数据
exports.importData =  async (req, res) => {
    console.log(req.body.str, 77777);

  let str = '';
  for (let item of req.body.str) {
    try {
      // 加密一次密码
      console.log(item.Password);
      const hashedPassword = await hashPassword(item.Password); // 密码加密

      // 构造 SQL 插入语句
      str += `('${item.Name}', '${item.Account}', '${item.PhoneNumber}', '${item.ICCardNumber}',` +
        `(select ID from role where RoleName='${item.RoleName}'), '${item.BuildingJurisdiction}',` +
        `'${item.CardType}', '${item.CardID}', '${hashedPassword}', '${item.Status}', '${item.IsLinkedToOperationalAccount}'),`;
    } catch (err) {
      console.error("Error while processing password:", err);
    }
  }

  // 移除最后一个逗号
  str = str.slice(0, -1);

  // 打印最终的 SQL 语句（注意：在生产环境中，不要直接执行字符串拼接的 SQL）
    var sql =
       `INSERT INTO employee (Name, Account, PhoneNumber, ICCardNumber, RoleID, BuildingJurisdiction, CardType, CardID,Password) VALUES${str.slice(0,str.length-1)}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send({
            status:200
        });
    });
}
//查看某个用户信息
exports.someEmolyee = (req, res) => {
    const { account } = req.body
    var sql =
        `select Name,Account,PhoneNumber,Password from employee where Account='${account}'`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send(data[0]);
    });
}